<?php

namespace App\Services\ApplyGoldRecordBatchExamine;

use Closure;
use App\Models\User;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class ApplyGoldRecordBatchExamineRequest extends FormRequest
{
	protected array $unpaidCacheIds = [];

	public function rules(): array
	{

		return [
			'records' => ['array', $this->records()],
			'examine_record'=>['required']
		];
	}

	public function records(): Closure
	{
		return function ($key, $value, $fail) {
			/**
			 * @var User $user
			 */
			$user = $this->user();

			$cachedIds = collect($value)->unique();

			if ($cachedIds->count() <= 0) {
				return $fail('请提供正确的抢购记录');
			}
			$examineRecord = request()->examine_record;

			foreach ($cachedIds as $cid) {

				if (! $user->isExamineRecordCache($examineRecord,$cid)) {
					return $fail('请提供正确的抢购记录');
				} elseif (! Redis::exists($cid)) {
					return $fail("目标记录不存在:{$cid}");
				} elseif (Redis::hGet($cid, 'is_examine')) {
					return $fail("目标记录已审核:{$cid}");
				} elseif (Redis::hGet($cid, 'is_paid')) {
					return $fail("目标记录已付款:{$cid}");
				}

			}

		
			$this->unpaidCacheIds = $cachedIds->toArray();

			return true;
		};
	}

	public function getUnpaidCacheIds(): array
	{
		return $this->unpaidCacheIds;
	}
}
